package com.wufeng.springcloud.controller;

import com.wufeng.springcloud.entities.CommonResult;
import com.wufeng.springcloud.entities.Payment;
import com.wufeng.springcloud.lb.MyLB;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/consumer/payment")
public class ConsumerController {
//    private static final String PAYMEN_URL = "http://localhost:8002";
    private static final String PAYMEN_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private MyLB loadBalancer;

    @GetMapping("/create")
    public CommonResult create(Payment payment) {
        return restTemplate.postForObject(PAYMEN_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/list/{id}")
    public CommonResult list(@PathVariable Long id) {
        return restTemplate.getForObject(PAYMEN_URL + "/payment/list/" + id, CommonResult.class);
    }

    @GetMapping("/get/{id}")
    public CommonResult listForEntity(@PathVariable Long id) {
        ResponseEntity<CommonResult> resultResponseEntity = restTemplate.getForEntity(PAYMEN_URL + "/payment/list/" + id, CommonResult.class);
        if (resultResponseEntity.getStatusCode().is2xxSuccessful()) {
            return resultResponseEntity.getBody();
        }else {
            return  new CommonResult(500,"获取失败");
        }
    }

    @GetMapping("/lb")
    public String getPaymentLB() {
        List<ServiceInstance> li = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (li == null || li.size() <= 0) {
            return "not find instance";
        }
        ServiceInstance instances = loadBalancer.instances(li);
        URI uri = instances.getUri();
        return restTemplate.getForObject(uri + "/payment/lb", String.class);
    }

}
